package cn.kgc.appinfo.controller;

import cn.kgc.appinfo.entity.AppInfo;
import cn.kgc.appinfo.entity.AppVersion;
import cn.kgc.appinfo.service.AppInfoService;
import cn.kgc.appinfo.service.AppVersionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpRequest;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.math.BigDecimal;

@Controller
@RequestMapping("/app_version")
public class AppVersionController {

    @Autowired
    private AppVersionService appVersionService;
    @Autowired
    private AppInfoService appInfoService;

    @RequestMapping("/save_new_version/{appId}")
    public String saveAppVersion(@PathVariable Integer appId, Model model){
        model.addAttribute("appId",appId);
        return "appVersion/saveNewVersion";
    }

    @RequestMapping("/do_save_new_version")
    public String doSaveAppVersion(AppVersion appVersion, MultipartFile upload, HttpServletRequest request) throws IOException {

        if(!upload.isEmpty()){
            String path = request.getServletContext().getRealPath("/uploads");

            File file = new File(path);
            if(!file.exists()){
                file.mkdir();
            }
            String originalFilename = upload.getOriginalFilename();
            appVersion.setDownloadLink("/uploads/"+originalFilename);
            //获取上传文件的大小
            appVersion.setVersionSize(new BigDecimal(upload.getSize()));

            appVersion.setApkFileName(upload.getOriginalFilename());

            upload.transferTo(new File(path,originalFilename));
        }
        appVersionService.saveAppVersion(appVersion);

        AppInfo appInfo = new AppInfo();
        appInfo.setVersionId(appVersion.getId());
        appInfo.setId(appVersion.getAppId());
        appInfoService.updataAppInfo(appInfo);

        return "redirect:/app_info/show_app";
    }
}
